package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class HuanXinTokenService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    public static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private String refreshToken() {
        //拼接环信token的url
        String url = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName() + "/"
                + this.huanXinConfig.getAppName() + "/token";

        try {
            //配置参数
            Map<String, String> param = new HashMap<>();
            param.put("grant_type", "client_credentials");
            param.put("client_id", this.huanXinConfig.getClientId());
            param.put("client_secret", this.huanXinConfig.getClientSecret());
            //发送请求
            ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, param, String.class);

            //判断是否成功
            if (responseEntity.getStatusCodeValue() == 200) {
                //获取数据
                String body = responseEntity.getBody();
                //转成可操作性的json对象
                JsonNode jsonNode = MAPPER.readTree(body);
                String access_token = jsonNode.get("access_token").asText();
                //存入redis
                this.redisTemplate.opsForValue().set(REDIS_KEY, access_token, Duration.ofDays(5));
                return access_token;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public String getToken() {
        String s = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if(StringUtils.isNotEmpty(s)){
            return s;
        }
        return refreshToken();
    }
}
